package apis

import (
	"github.com/gin-gonic/gin"
	"tylnmall/models"
	"common/logger"
	"net/http"
	"tylnmall/constant"
	"github.com/jinzhu/gorm"
	"errors"
	"fmt"
	"math"
)

//根据用户id获取用户购物列表
func PurchaseListApi(c *gin.Context) {
	type param struct {
		Id    int `json:"id" form:"id"`
		Page  int `json:"page" form:"page"`
		Limit int `json:"limit" form:"limit"`
	}
	type pur struct {
		Id                 int     `json:"id"`
		CommodityId        int     `json:"commodity_id"`
		CommodityName      string  `json:"commodity_name"`
		CommodityUnitPrice float32 `json:"commodity_unit_price"`
		CommodityUrl       string  `json:"commodity_url"`
		Number             int     `json:"number"`
	}
	var p param
	var err error
	var purchase []*models.PurchaseHistory
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	db := c.MustGet("ty").(*gorm.DB)
	var count float64
	if err := db.Where("user_id = ?", p.Id).Model(&models.PurchaseHistory{}).Count(&count).Error; err != nil {
		logger.Error(err)
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	if p.Limit == 0 {
		p.Limit = 6
	}
	if p.Page == 0 {
		p.Page = 1
	} else if float64(p.Page) > math.Ceil(count/float64(p.Limit)) {
		p.Page = 1
	}

	if err = db.Limit(p.Limit).Offset((p.Page - 1) * p.Limit).Where("user_id = ?", p.Id).Find(&purchase).Error; err != nil {
		logger.Error(err)
		err = errors.New("purchase not found")
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	var list []*pur
	fmt.Println(len(purchase))
	for _, car := range purchase {
		var l pur
		var commodity models.Commodity
		l.Id = car.Id
		l.Number = car.Number
		if err = db.Where("id = ?", car.CommodityId).Find(&commodity).Error; err != nil {
			logger.Error(err)
			err = errors.New("commodity not found")
			logger.Error(err)
			c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
			return
		}
		l.CommodityId = car.CommodityId
		l.CommodityName = commodity.Name
		l.CommodityUnitPrice = commodity.UnitPrice
		l.CommodityUrl = commodity.Image
		list = append(list, &l)
	}
	a := p.Limit
	c.JSON(http.StatusOK, gin.H{"list": &list, "pageNum": math.Ceil(count / float64(a))})
}

//直接购买商品
func BuyApi(c *gin.Context) {
	type param struct {
		Userid      int `json:"userid" form:"userid"`
		Commodityid int `json:"commodityid" form:"commodityid"`
		Num         int `json:"num" form:"num"`
	}
	var p param
	var err error
	var purchase models.PurchaseHistory
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	purchase.Number = p.Num
	purchase.CommodityId = p.Commodityid
	purchase.UserId = p.Userid
	db := c.MustGet("ty").(*gorm.DB)
	if err = db.Create(&purchase).Error; err != nil {
		logger.Error(err)
		err = errors.New("purchase not found")
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	c.JSON(http.StatusOK, gin.H{"status": "success"})
}
